package com.qiguliuxing.dts.common.plugins;

import com.qiguliuxing.dts.common.constant.CommConsts;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.*;

/**
 * 用于生成Swagger2 模型层注解的扩展插件
 * 因为在 插件需要已jar的方式引用，该类放common模块，需要install到本地maven库后再执行mybatis逆向代码的生成
 * @author qinguliuxing
 * @since 1.0.0
 */
public class Swagger2DocPlugin extends PluginAdapter {
    private static final Map<String, String> ANNOTATION_IMPORTS = new HashMap(CommConsts.INIT_HASH_MAP_SIZE);
    private List<String> annotations;

    public Swagger2DocPlugin() {
    }

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        super.initialized(introspectedTable);
        this.annotations = new ArrayList();
        this.annotations.add(0, "@ApiModel");
        this.annotations.add(1, "@ApiModelProperty");
    }

    static {
        ANNOTATION_IMPORTS.put("@ApiModel", "io.swagger.annotations.ApiModel");
        ANNOTATION_IMPORTS.put("@ApiModelProperty", "io.swagger.annotations.ApiModelProperty");
    }

    @Override
    public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
        Iterator var4 = this.annotations.iterator();
        while (var4.hasNext()) {
            String annotation = (String) var4.next();
            if ("@ApiModel".equals(annotation)) {
                String modelDesc = introspectedTable.getRemarks();
                if (StringUtils.isBlank(modelDesc)) {
                    String beanName = topLevelClass.getType().getShortName();
                    modelDesc = beanName + "实体对象";
                }
                String classAnnotation = "@ApiModel(value=\"" + modelDesc  + "\")";
                if (!topLevelClass.getAnnotations().contains(classAnnotation)) {
                    topLevelClass.addAnnotation(classAnnotation);
                }
            } else if ("@ApiModelProperty".equals(annotation)) {
                field.addAnnotation("@ApiModelProperty(value=\"" + introspectedColumn.getRemarks() + "\")");
            }
            topLevelClass.addImportedType(ANNOTATION_IMPORTS.get(annotation));
        }
        return super.modelFieldGenerated(field, topLevelClass, introspectedColumn, introspectedTable, modelClassType);
    }

}
